<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="菜单名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button type="success" icon="plus" @click="handleOpenDialog('0')">新增</el-button>
        </div>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        row-key="id"
        :data="menuTableData"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }"
        class="data-table__content"
        @row-click="handleRowClick"
      >
        <el-table-column label="菜单名称" align="left" width="200">
          <template #default="scope">
            <!-- <div style="display: flex"> -->
            <!-- <template v-if="scope.row.menuIcon && scope.row.menuIcon.startsWith('el-icon')">
                <el-icon style="vertical-align: -0.15em">
                  <component :is="scope.row.menuIcon.replace('el-icon-', '')" />
                </el-icon>
              </template>
              <template v-else-if="scope.row.menuIcon">
                <div :class="`i-svg:${scope.row.menuIcon}`" />
              </template> -->
            {{ scope.row.menuName }}
            <!-- </div> -->
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" width="100" prop="sort" />

        <el-table-column label="类型" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.menuType === 1" type="warning">目录</el-tag>
            <el-tag v-if="scope.row.menuType === 2" type="success">菜单</el-tag>
            <el-tag v-if="scope.row.menuType === 3" type="danger">按钮</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="路由地址" align="center" prop="routerAddress" />
        <el-table-column label="组件路径" align="center" prop="path" />

        <el-table-column label="权限标识" align="center" prop="permissionCharacters" />
        <!-- <el-table-column label="创建时间" align="center" width="300" prop="createTime" /> -->
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.showStatus === 1" type="success">显示</el-tag>
            <el-tag v-else type="info">隐藏</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="320">
          <template #default="scope">
            <el-button
              v-if="scope.row.menuType == 1 || scope.row.menuType == 2"
              v-hasPerm="['system:menu:add']"
              type="primary"
              link
              size="small"
              icon="plus"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              新增
            </el-button>

            <el-button
              v-hasPerm="['system:menu:edit']"
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(scope.row.id, scope.row.id, scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-hasPerm="['system:menu:delete']"
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="35%"
      draggable
      @close="handleCloseDialog"
    >
      <el-form ref="menuFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="上级菜单" prop="menuPid">
          <el-tree-select
            v-model="formData.menuPid"
            placeholder="选择上级菜单"
            :data="menuOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-radio-group v-model="formData.menuType" @change="handleMenuTypeChange">
            <el-radio :value="MenuTypeEnum.CATALOG">目录</el-radio>
            <el-radio :value="MenuTypeEnum.MENU">菜单</el-radio>
            <el-radio :value="MenuTypeEnum.BUTTON">按钮</el-radio>
            <!-- <el-radio :value="MenuTypeEnum.EXTLINK">外链</el-radio> -->
          </el-radio-group>
        </el-form-item>
        <el-row>
          <el-col v-if="formData.menuType !== MenuTypeEnum.BUTTON" :span="24">
            <el-form-item label="图标" prop="icon">
              <!-- 图标选择器 -->
              <icon-select v-model="formData.icon" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="formData.menuType == 1 || formData.menuType == 2"
              label="菜单名称"
              prop="menuName"
            >
              <el-input v-model="formData.menuName" placeholder="请输入菜单名称" />
            </el-form-item>
            <el-form-item v-else label="按钮名称" prop="menuName">
              <el-input v-model="formData.menuName" placeholder="请输入按钮名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number
                v-model="formData.sort"
                style="width: 100px"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="formData.menuType !== MenuTypeEnum.BUTTON" :span="12">
            <el-form-item prop="showStatus" label="显示状态">
              <el-radio-group v-model="formData.showStatus">
                <el-radio :value="1">显示</el-radio>
                <el-radio :value="0">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="permissionCharacters" label="权限字符">
              <el-input
                v-model="formData.permissionCharacters"
                placeholder="请输入权限字符"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col v-if="formData.menuType !== MenuTypeEnum.BUTTON" :span="12">
            <el-form-item prop="isLink" label="是否外链">
              <el-radio-group v-model="formData.isLink">
                <el-radio :value="0">是</el-radio>
                <el-radio :value="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col
            v-if="
              formData.menuType == MenuTypeEnum.CATALOG || formData.menuType == MenuTypeEnum.MENU
            "
            :span="12"
          >
            <el-form-item prop="routerAddress">
              <template #label>
                <div class="flex-y-center">路由地址</div>
              </template>
              <el-input v-model="formData.routerAddress" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="formData.menuType == MenuTypeEnum.MENU" prop="path">
              <template #label>
                <div class="flex-y-center">
                  组件路径
                  <el-tooltip placement="bottom" effect="light">
                    <template #content>
                      组件页面完整路径，相对于 src/views/，如 system/user/index，缺省后缀 .vue
                    </template>
                    <el-icon class="ml-1 cursor-pointer">
                      <QuestionFilled />
                    </el-icon>
                  </el-tooltip>
                </div>
              </template>

              <el-input v-model="formData.path" placeholder="system/user/index" style="width: 95%">
                <template v-if="formData.menuType == MenuTypeEnum.MENU" #prepend>
                  src/views/
                </template>
                <template v-if="formData.menuType == MenuTypeEnum.MENU" #append>.vue</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-form-item v-if="formData.type == MenuTypeEnum.EXTLINK" label="外链地址" prop="path">
          <el-input v-model="formData.routePath" placeholder="请输入外链完整路径" />
        </el-form-item> -->

        <!-- <el-form-item v-if="formData.type == MenuTypeEnum.CATALOG" label="跳转路由">
          <el-input v-model="formData.redirect" placeholder="跳转路由" />
        </el-form-item> -->

        <!-- <el-form-item v-if="formData.type == MenuTypeEnum.MENU">
          <template #label>
            <div class="flex-y-center">
              路由参数
              <el-tooltip placement="bottom" effect="light">
                <template #content>
                  组件页面使用 `useRoute().query.参数名` 获取路由参数值。
                </template>
                <el-icon class="ml-1 cursor-pointer">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>

          <div v-if="!formData.params || formData.params.length === 0">
            <el-button type="success" plain @click="formData.params = [{ key: '', value: '' }]">
              添加路由参数
            </el-button>
          </div>

          <div v-else>
            <div v-for="(item, index) in formData.params" :key="index">
              <el-input v-model="item.key" placeholder="参数名" style="width: 100px" />

              <span class="mx-1">=</span>

              <el-input v-model="item.value" placeholder="参数值" style="width: 100px" />

              <el-icon
                v-if="formData.params.indexOf(item) === formData.params.length - 1"
                class="ml-2 cursor-pointer color-[var(--el-color-success)]"
                style="vertical-align: -0.15em"
                @click="formData.params.push({ key: '', value: '' })"
              >
                <CirclePlusFilled />
              </el-icon>
              <el-icon
                class="ml-2 cursor-pointer color-[var(--el-color-danger)]"
                style="vertical-align: -0.15em"
                @click="formData.params.splice(formData.params.indexOf(item), 1)"
              >
                <DeleteFilled />
              </el-icon>
            </div>
          </div>
        </el-form-item> -->

        <!-- <el-form-item
          v-if="formData.type === MenuTypeEnum.CATALOG || formData.type === MenuTypeEnum.MENU"
        >
          <template #label>
            <div class="flex-y-center">
              始终显示
              <el-tooltip placement="bottom" effect="light">
                <template #content>
                  选择"是"，即使目录或菜单下只有一个子节点，也会显示父节点。
                  <br />
                  选择"否"，如果目录或菜单下只有一个子节点，则只显示该子节点，隐藏父节点。
                  <br />
                  如果是叶子节点，请选择"否"。
                </template>
                <el-icon class="ml-1 cursor-pointer">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>

          <el-radio-group v-model="formData.alwaysShow">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item> -->

        <!-- <el-form-item v-if="formData.type === MenuTypeEnum.MENU" label="缓存页面">
          <el-radio-group v-model="formData.keepAlive">
            <el-radio :value="1">开启</el-radio>
            <el-radio :value="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from "@/store/modules/app.store";
import { DeviceEnum } from "@/enums/settings/device.enum";

import MenuAPI, { MenuQuery, MenuForm, MenuVO } from "@/api/system/menu.api";
import { MenuTypeEnum } from "@/enums/system/menu.enum";
import { spaceItemProps } from "element-plus";

defineOptions({
  name: "SysMenu",
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryFormRef = ref();
const menuFormRef = ref();

const loading = ref(false);
const dialog = reactive({
  title: "新增菜单",
  visible: false,
});

const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));
// 查询参数
const queryParams = reactive<MenuQuery>({});
// 菜单表格数据
const menuTableData = ref<MenuVO[]>([]);
// 顶级菜单下拉选项
const menuOptions = ref<OptionType[]>([]);
// 初始菜单表单数据
const initialMenuFormData = ref<MenuForm>({
  id: undefined,
  menuPid: "0",
  sort: 1,
  menuType: MenuTypeEnum.MENU, // 默认菜单
  routerAddress: "",
  isLink: 1,
  path: "",
  alwaysShow: 2,
  // keepAlive: 1,
  showStatus: 1,
  permissionCharacters: "",
});
// 菜单表单数据
const formData = ref({ ...initialMenuFormData.value });
// 表单验证规则
const rules = reactive({
  menuPid: [{ required: true, message: "请选择上级菜单", trigger: "blur" }],
  menuName: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  menuType: [{ required: true, message: "请选择菜单类型", trigger: "blur" }],
  permissionCharacters: [{ required: true, message: "请选择字符权限", trigger: "blur" }],
});

// 选择表格的行菜单ID
const selectedMenuId = ref<string | undefined>();

// 查询菜单
function handleQuery() {
  loading.value = true;
  MenuAPI.getList(queryParams)
    .then((data) => {
      menuTableData.value = data.data.data;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 行点击事件
function handleRowClick(row: MenuVO) {
  selectedMenuId.value = row.id;
}

const transformNode = (node) => {
  const transformed = {
    value: node.id.toString(),
    label: node.menuName,
    type: node.menuType,
  };
  const children = node.children;

  if (Array.isArray(children) && children.length > 0) {
    if (children) transformed.children = children.map((child) => transformNode(child)); // 递归处理子数组
  } else {
    transformed.children = []; // 统一处理为空数组（避免后续渲染报错）
  }
  return transformed;
};
/**
 * 递归过滤树形结构中 type 为 3 的节点
 * @param {Array} nodes - 当前层级的节点数组
 * @returns 过滤后的节点数组
 */
const filterTree = (nodes) => {
  // 1. 过滤当前层级：排除 type 为 3 的节点
  return (
    nodes
      .filter((node) => node.menuType !== 3)
      // 2. 递归处理子节点（如果有）
      .map((node) => {
        // 若当前节点有子节点，递归过滤子节点
        if (Array.isArray(node.children) && node.children.length > 0) {
          return {
            ...node, // 保留当前节点的其他属性
            children: filterTree(node.children), // 递归过滤子节点
          };
        }
        // 没有子节点或子节点为空，直接返回当前节点
        return node;
      })
  );
};
/**
 * 打开表单弹窗
 *
 * @param menuPid 父菜单ID
 * @param menuId 菜单ID
 * @param val  行数据
 *
 */
function handleOpenDialog(menuPid?: string, menuId?: string, val?: object) {
  MenuAPI.getList(true)
    .then((data) => {
      const newObj = filterTree(data.data.data).map((rootNode) => transformNode(rootNode));
      menuOptions.value = [{ value: "0", label: "主类目", children: newObj }];
    })
    .then(() => {
      dialog.visible = true;
      if (menuId) {
        dialog.title = "编辑菜单";
        console.log("编辑菜单", val);
        formData.value.menuPid = val.menuPid.toString();
        formData.value.id = val.id;
        formData.value.menuIcon = val.menuIcon;
        formData.value.menuName = val.menuName;
        formData.value.menuType = val.menuType;
        formData.value.isLink = val.isLink;
        formData.value.path = val.path;
        formData.value.routerAddress = val.routerAddress;
        formData.value.permissionCharacters = val.permissionCharacters;
        formData.value.showStatus = val.showStatus;
        formData.value.sort = val.sort;
        // MenuAPI.getFormData(menuId).then((data) => {
        //   initialMenuFormData.value = { ...data };
        //   formData.value = data;
        // });
      } else {
        dialog.title = "新增菜单";
        formData.value.menuPid = menuPid?.toString();
      }
    });
}
// const handleNodeClick = (data: Tree) => {
//   console.log(data);
//   formData.value.menuPid = data.value?.toString();
// };

// 菜单类型切换
function handleMenuTypeChange() {
  // 如果菜单类型改变
  if (formData.value.type !== initialMenuFormData.value.type) {
    if (formData.value.type === MenuTypeEnum.MENU) {
      // 目录切换到菜单时，清空组件路径
      if (initialMenuFormData.value.type === MenuTypeEnum.CATALOG) {
        formData.value.component = "";
      } else {
        // 其他情况，保留原有的组件路径
        formData.value.routePath = initialMenuFormData.value.routePath;
        formData.value.component = initialMenuFormData.value.component;
      }
    }
  }
}

/**
 * 提交表单
 */
function handleSubmit() {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      const menuId = formData.value.id;
      console.log("新增", formData.value);

      if (menuId) {
        //修改时上级菜单不能为当前菜单
        if (formData.value.menuPid == menuId) {
          ElMessage.error("上级菜单不能为当前菜单");
          return;
        }
        console.log("菜单", formData.value);

        MenuAPI.update(menuId, formData.value).then(() => {
          ElMessage.success("修改成功");
          handleCloseDialog();
          handleQuery();
        });
      } else {
        if (formData.value.menuType == 1) {
          //目录
          formData.value.path = "Layout";
        }
        console.log("111", formData.value);

        MenuAPI.create(formData.value).then(() => {
          ElMessage.success("新增成功");
          handleCloseDialog();
          handleQuery();
        });
      }
    }
  });
}

// 删除菜单
function handleDelete(menuId: string) {
  if (!menuId) {
    ElMessage.warning("请勾选删除项");
    return false;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      MenuAPI.deleteById(menuId)
        .then(() => {
          ElMessage.success("删除成功");
          handleQuery();
        })
        .finally(() => {
          loading.value = false;
        });
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

function resetForm() {
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();
  formData.value = {
    id: undefined,
    menuPid: "0",
    path: "",
    sort: 1,
    menuType: MenuTypeEnum.MENU, // 默认菜单
    routerAddress: "",
    isLink: 1,
    alwaysShow: 2,
    showStatus: 1,
    permissionCharacters: "",
  };
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>
<style lang="scss" scoped>
:deep(.el-dialog__title) {
  color: #000;
}
:deep(.el-form-item--label-right .el-form-item__label) {
  font-weight: bold;
}
</style>
